package edu.nju.login.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.nju.login.listeners.LoginListener;

/**
 * Servlet implementation class CookieServlet
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CookieServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		handleRequest(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		handleRequest(request, response);

	}

	private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession(false);

		// Try to retrieve the cookie from the request.
		boolean cookieFound = false;

		Cookie cookie = null;
		Cookie[] cookies = req.getCookies();
		if (null != cookies) {
			// Look through all the cookies and see if the
			// cookie with the login info is there.
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (cookie.getName().equals("LoginCookie")) {
					cookieFound = true;
					break;
				}
			}
		}



//		if(session==null){
			String loginValue = req.getParameter("login");
			boolean isLoginAction = (null == loginValue) ? false : true;

			if (isLoginAction) { // User is logging in

				if (cookieFound) { // If the cookie exists update the value only if changed
					if (!loginValue.equals(cookie.getValue())) {
						cookie.setValue(loginValue);
						resp.addCookie(cookie);
					}
				} else {
					// If the cookie does not exist, create it and set value
					cookie = new Cookie("LoginCookie", loginValue);
					cookie.setMaxAge(Integer.MAX_VALUE);
					// System.out.println("Add cookie");
					resp.addCookie(cookie);
				}

				// create a session to show that we are logged in
//				session = req.getSession(true);            
				session.setAttribute("login",loginValue);
				req.setAttribute("login",loginValue);
				displayLogoutPage(req, resp);
			}
			else{
				// Display the login page. If the cookie exists, set login
				resp.sendRedirect(req.getContextPath() + "/Login");
			}
//		}
//		else{
//
//			String loginValue = session.getAttribute("login").toString();
//			req.setAttribute("login",loginValue);
//			displayLogoutPage(req, resp);
//		}


	}


	public void displayLogoutPage(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		int pageCounter = LoginListener.getMember();

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html><body>");
		out.println("<p>Welcome " + req.getAttribute("login") + "</p>");
		out.println("<form method='GET' action='"
				+ res.encodeURL(req.getContextPath() + "/Login") + "'>");
		out.println("Click <a href='" + res.encodeURL(req.getRequestURI())
				+ "'>here</a> to reload this page.<br>");
		out.println("</p>");
		out.println("<input type='submit' name='Logout' value='Logout'>");
		out.println("</form>");

		out.println("There are " + pageCounter + " member logged in.");

		out.println("<p>Servlet is version @version@</p>");

		out.println("</body></html>");
	}


}
